#include "mainwindow.h"

#include <QCloseEvent>
#include <QDateTime>
#include <QDebug>
#include <QMessageBox>
#include <QSettings>
#include <QStandardItem>
#include <QStyle>

#include "addadmindialog.h"
#include "addbookdialog.h"
#include "ui_mainwindow.h"

int MainWindow::exitCode = -123456789;

// 表示各种下拉列表的值
enum BOOK_FILTER_TYPE {
    BOOK_NAME = 0,
    BOOK_DOMAIN,
    BOOK_NUMBER,
    BOOK_AUTHOR,
    BOOK_PUBLISH
};

// 用来初始化各种QTableWidget的函数
void initBookTable(Database *database, QTableWidget *tableWidget);

void initStudentTable(Database *database, QTableWidget *tableWidget);

void initAdminTable(Database *database, QTableWidget *tableWidget);

void initBorrowTable(Database *database, QTableWidget *tableWidget);

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    // 设置窗口大小以及图标
    setFixedSize(950, 600);
    QStyle *style = QApplication::style();
    QIcon picture = style->standardIcon(QStyle::SP_DesktopIcon);
    setWindowIcon(picture);

    // 从配置文件中加载登录信息
    QString account;
    QSettings login("./login.ini", QSettings::IniFormat);
    account = login.value("login/account").toString();
    isAdmin = login.value("login/is_admin").toBool();

    // 根据登录用户调整界面
    if (isAdmin) {
        // 隐藏左侧导航栏的搜索和借书/还书
        ui->g_search->setDisabled(true);
        ui->g_return->setDisabled(true);
        ui->g_search->hide();
        ui->g_return->hide();

        // 隐藏index页面的搜索/借书&还书按钮
        ui->b_return->hide();
        ui->b_search->hide();
        ui->b_return->setDisabled(true);
        ui->b_search->setDisabled(true);
    } else {
        // 隐藏左侧导航栏的人员/图书管理按钮
        ui->g_book->setDisabled(true);
        ui->g_person->setDisabled(true);
        ui->g_book->hide();
        ui->g_person->hide();

        // 隐藏index页面的人员/图书管理按钮
        ui->b_person->hide();
        ui->b_book->hide();
        ui->b_person->setDisabled(true);
        ui->b_book->setDisabled(true);
    }

    this->database = Database::getInstance();
    this->database->connectDatabase();
    this->database->openDatabase();
    if (!database->isDatabaseOpen()) {
        QMessageBox::critical(this, "错误", "数据库连接错误");
        QApplication::exit();
    }

    // 根据登录用户从数据库中加载数据
    if (isAdmin) {
        // 管理员
        QString sql =
            QString(
                "SELECT account, password FROM admin_info WHERE account='") +
            account + "';";
        database->exec(sql);

        qDebug() << sql;
        QSqlQuery *query = database->getQuery();
        if (query->next()) {
            adminAccount = query->value("account").toString();
            adminPassword = query->value("password").toString();
        } else {
            QMessageBox::critical(this, "错误", "数据获取错误");
            QApplication::exit();
        }

        qDebug() << adminAccount << endl << adminPassword;
    } else {
        // 学生
        QString sql = QString(
                          "SELECT id, name, account, password, sex, "
                          "borrow_book FROM student_info WHERE account='") +
                      account + "';";
        QSqlQuery *query;
        database->exec(sql);

        qDebug() << sql;
        query = database->getQuery();
        query->next();
        // 存储当前登录学生的信息
        studentId = query->value("id").toInt();
        studentName = query->value("name").toString();
        studentAccount = query->value("account").toString();
        studentPassword = query->value("password").toString();
        studentSex = static_cast<StudentSex>(query->value("sex").toInt());
        studentBorrowBook = query->value("borrow_book").toInt();
        if (studentName.length() == 0) {
            studentName = QString("Student ") + studentAccount;
        }

        // 查看借阅书目是否有超出时间的，有就使用一个提示框进行提示
        qDebug() << "开始查找有没有超过借阅期限的图书";
        sql = QString(
                  "SELECT book_name, borrow_time FROM borrow_info WHERE "
                  "student_account=") +
              studentAccount;
        database->exec(sql);

        QStringList bookNameList;
        int borrowBooks = 0;
        query = database->getQuery();
        // 这里进行时间的比较
        QDateTime currentTime = QDateTime::currentDateTime();
        while (query->next()) {
            QString borrowTimeStr = query->value("borrow_time").toString();
            QDateTime borrowTime =
                QDateTime::fromString(borrowTimeStr, "yyyy-MM-dd hh:mm:ss");
            if ((currentTime.toTime_t() - borrowTime.toTime_t()) >
                (60 * 24 * 60 * 60)) {
                bookNameList.push_back(query->value("book_name").toString());
                borrowBooks++;
            }
        }
        if (borrowBooks > 0) {
            QString borrowBookStr;
            for (int i = 0; i < bookNameList.size(); i++) {
                borrowBookStr += bookNameList[i];
                borrowBookStr += ";\n";
            }
            borrowBookStr =
                QString("您下列图书超过借阅最后期限，请尽快归还：\n") +
                borrowBookStr;
            QMessageBox::information(this, "您有未归还的图书", borrowBookStr);
        }
    }

    // 将页面切换到index页面上
    ui->stackedWidget->setCurrentWidget(ui->p_index);

    // 再次加载页面
    QMap<QString, int> filterTypes;
    filterTypes.insert("图书名称", BOOK_NAME);
    filterTypes.insert("专业领域", BOOK_DOMAIN);
    filterTypes.insert("图书编号", BOOK_NUMBER);
    filterTypes.insert("图书作者", BOOK_AUTHOR);
    filterTypes.insert("出版社", BOOK_PUBLISH);
    if (isAdmin) {
        // 图书管理页面的界面初始化
        // 下拉列表内容的初始化
        for (const QString &str : filterTypes.keys()) {
            ui->book_type->addItem(str, filterTypes.value(str));
        }
        initBookTable(database, ui->bookTable);
        initStudentTable(database, ui->personTable);
    } else {
        // 学生登录需要的页面的初始化
        for (const QString &str : filterTypes.keys()) {
            ui->book_type2->addItem(str, filterTypes.value(str));
        }
        initBookTable(database, ui->bookTable2);
        initBorrowTable(database, ui->borrowTable);
    }

    ui->line->hide();
    ui->label_22->hide();
    ui->label_23->hide();
    ui->label_24->hide();
    ui->label_25->hide();
    ui->confirm->hide();
    ui->confirm->setDisabled(true);
    ui->cancel->hide();
    ui->cancel->setDisabled(true);
    ui->new_name->hide();
    ui->new_name->setDisabled(true);
    ui->new_account->hide();
    ui->new_account->setDisabled(true);
    ui->new_password->hide();
    ui->new_password->setDisabled(true);
    ui->choose_sex->hide();
    ui->choose_sex->setDisabled(true);
    if (isAdmin) {
        ui->d_account->setText(adminAccount);
        ui->d_password->setText(adminPassword);
        ui->d_account->setReadOnly(true);
        ui->d_password->setReadOnly(true);
        ui->label_7->hide();
        ui->label_24->hide();
        ui->d_sex->hide();
        ui->choose_sex->hide();
        ui->label_7->setDisabled(true);
        ui->label_24->setDisabled(true);
        ui->d_sex->setDisabled(true);
        ui->choose_sex->setDisabled(true);
        ui->label_8->hide();
        ui->d_name->hide();
        ui->d_name->setDisabled(true);
    } else {
        ui->d_name->setText(studentName);
        ui->d_account->setText(studentAccount);
        ui->d_password->setText(studentPassword);
        if (studentSex == MALE) {
            ui->d_sex->setText("男");
        } else if (studentSex == FEMALE) {
            ui->d_sex->setText("女");
        } else if (studentSex == UNKNOWN) {
            ui->d_sex->setText("未知");
        }
        ui->choose_sex->addItem("男", 0);
        ui->choose_sex->addItem("女", 1);
        ui->choose_sex->addItem("未知", 2);
    }
}

void initBookTable(Database *database, QTableWidget *tableWidget) {
    database = Database::getInstance();
    database->connectDatabase();
    database->openDatabase();

    tableWidget->setColumnCount(9);
    tableWidget->setHorizontalHeaderLabels(
        QString("Id,名称,作者,出版社,编号,专业领域,价格,出版时间,是否借出")
            .split(","));
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableWidget->setSortingEnabled(true);

    int columns;
    database->exec("select count(*) as row from book_info");
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    tableWidget->setRowCount(columns);

    database->exec("SELECT * FROM book_info;");

    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        tableWidget->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        tableWidget->setItem(
            i, 1, new QTableWidgetItem(query->value("book_name").toString()));
        tableWidget->setItem(
            i, 2, new QTableWidgetItem(query->value("book_author").toString()));
        tableWidget->setItem(
            i, 3,
            new QTableWidgetItem(query->value("book_publish").toString()));
        tableWidget->setItem(
            i, 4, new QTableWidgetItem(query->value("book_number").toString()));
        tableWidget->setItem(
            i, 5, new QTableWidgetItem(query->value("book_domain").toString()));
        tableWidget->setItem(
            i, 6, new QTableWidgetItem(query->value("book_price").toString()));
        tableWidget->setItem(
            i, 7, new QTableWidgetItem(query->value("book_date").toString()));
        if (query->value("is_borrowed").toInt() == 0) {
            tableWidget->setItem(i, 8, new QTableWidgetItem("否"));
        } else {
            tableWidget->setItem(i, 8, new QTableWidgetItem("是"));
        }
    }
}

MainWindow::~MainWindow() {
    delete ui;
    this->database->closeDatabase();
}

// 这是左侧导航栏的按钮被按下之后的动作
void MainWindow::on_g_index_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_index);
    qDebug() << "切换到 index 页面";
}

void MainWindow::on_g_search_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_search);
    qDebug() << "切换到 search 页面";
}

void MainWindow::on_g_profile_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_profile);
    qDebug() << "切换到 profile 页面";
}

void MainWindow::on_g_book_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_book);
    qDebug() << "切换到 book 页面";
}

void MainWindow::on_g_person_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_person);
    qDebug() << "切换到 person 页面";
}

void MainWindow::on_g_logout_clicked() {
    if (QMessageBox::question(this, "退出", "确定要退出登录吗？",
                              QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::Yes) {
        // 这里可能还会做一些清理工作，比如关闭数据库的连接等
        QApplication::exit(MainWindow::exitCode);
    }
    /* 除了上面的之外，这里还有几种写法
     * 1. qApp->exit(-123456789);  // 但是是子类调用基类方法，IDE会有警告
     * 2. QApplication::instance()->exit(-123456789);  // 这个也会有警告
     * 至于分别是什么警告，自己复制一下代码写一下就会看到了
     * 不过仅限于CLion这种大型IDE，Qt Creator这种轻量级IDE是不会显示警告的
     * 但是CLion没有官方Qt插件也很让人苦恼，所有的函数都是没有被用到的，看起来很难受
     * */
}

void MainWindow::on_g_exit_clicked() { close(); }

void MainWindow::closeEvent(QCloseEvent *event) {
    // 主窗口关闭时执行的动作，弹出对话框，避免误触关闭
    if (QMessageBox::question(this, "退出", "确定要退出吗？",
                              QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::No) {
        event->ignore();
    } else {
        // 这里可能还会做一些清理工作，比如关闭数据库的连接等
        close();
    }
}

// 这是index页面按钮被按下之后的行为
void MainWindow::on_b_about_clicked() {
    QString aboutInfo = QString("面向对象的程序设计（C++）课程设计项目\n");
    aboutInfo += "选择题目为：图书管理系统\n";
    aboutInfo += "代码托管于：https://gitee.com/lielie4780/cpp_design\n";
    aboutInfo += "制作人员：孙强 <1604070358@qq.com>\n";
    aboutInfo += "©2020 lielie4780 版权所有";
    QMessageBox::information(this, "图书管理系统", aboutInfo);
}

void MainWindow::on_b_return_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_return);
}

void MainWindow::on_b_search_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_search);
}

void MainWindow::on_g_return_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_return);
}

void MainWindow::on_b_person_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_person);
}

void MainWindow::on_b_book_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_book);
}

void MainWindow::on_b_profile_clicked() {
    ui->stackedWidget->setCurrentWidget(ui->p_profile);
}

// 这是book页面的各种行为
void MainWindow::on_b_filter_book_clicked() {
    QString value = ui->bookEdit->text();
    if (value.length() == 0) {
        return;
    }
    QString key;
    // 备注，这里可以用QMap，但是不怎么了解，就先这样吧，只是写着麻烦点
    switch (ui->book_type->currentIndex()) {
        case BOOK_NAME:
            key = "book_name";
            break;
        case BOOK_DOMAIN:
            key = "book_domain";
            break;
        case BOOK_AUTHOR:
            key = "book_author";
            break;
        case BOOK_PUBLISH:
            key = "book_publish";
            break;
        case BOOK_NUMBER:
            key = "book_number";
            break;
        default:
            return;
            break;
    }

    int columns;
    QString sql;
    sql = QString("select count(*) as row from book_info WHERE ") + key + "='" +
          value + "';";
    database->exec(sql);
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    if (columns == 0) {
        QMessageBox::information(this, "没有数据", "没有符合条件的结果");
        ui->bookEdit->clear();
        return;
    }
    ui->bookTable->setRowCount(columns);
    sql = QString("SELECT * FROM book_info WHERE ") + key + "='" + value + "';";
    database->exec(sql);
    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        ui->bookTable->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        ui->bookTable->setItem(
            i, 1, new QTableWidgetItem(query->value("book_name").toString()));
        ui->bookTable->setItem(
            i, 2, new QTableWidgetItem(query->value("book_author").toString()));
        ui->bookTable->setItem(
            i, 3,
            new QTableWidgetItem(query->value("book_publish").toString()));
        ui->bookTable->setItem(
            i, 4, new QTableWidgetItem(query->value("book_number").toString()));
        ui->bookTable->setItem(
            i, 5, new QTableWidgetItem(query->value("book_domain").toString()));
        ui->bookTable->setItem(
            i, 6, new QTableWidgetItem(query->value("book_price").toString()));
        ui->bookTable->setItem(
            i, 7, new QTableWidgetItem(query->value("book_date").toString()));
        if (query->value("is_borrowed").toInt() == 0) {
            ui->bookTable->setItem(i, 8, new QTableWidgetItem("否"));
        } else {
            ui->bookTable->setItem(i, 8, new QTableWidgetItem("是"));
        }
    }
}

void MainWindow::on_b_rollback_book_clicked() {
    ui->bookEdit->clear();
    initBookTable(database, ui->bookTable);
}

void MainWindow::on_b_add_book_clicked() {
    QSettings addItemSettings("./book.ini", QSettings::IniFormat);
    AddBookDialog bookDialog;
    if (bookDialog.exec() == QDialog::Accepted) {
        QString bookName = addItemSettings.value("book/book_name").toString();
        QString bookNumber =
            addItemSettings.value("book/book_number").toString();
        QString bookAuthor =
            addItemSettings.value("book/book_author").toString();
        QString bookPublish =
            addItemSettings.value("book/book_publish").toString();
        QString bookDomain =
            addItemSettings.value("book/book_domain").toString();
        float bookPrice = addItemSettings.value("book/book_price").toFloat();
        QString bookDate = addItemSettings.value("book/book_date").toString();
        QString sql = QString(
                          "INSERT INTO book_info VALUES (null, '%1', '%2', "
                          "'%3', %4, '%5', '%6', '%7', %8);")
                          .arg(bookName)
                          .arg(bookDomain)
                          .arg(bookNumber)
                          .arg(bookPrice)
                          .arg(bookAuthor)
                          .arg(bookPublish)
                          .arg(bookDate)
                          .arg(0);
        if (!database->exec(sql)) {
            QMessageBox::warning(this, "错误", "图书编号重复");
            return;
        }
        initBookTable(database, ui->bookTable);
    }
}

void MainWindow::on_b_delete_book_clicked() {
    if (QMessageBox::warning(this, "删除图书", "确定要删除这本图书吗?",
                             QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::Yes) {
        int row = ui->bookTable->currentRow();
        if (ui->bookTable->item(row, 8)->text() == QString("是")) {
            QMessageBox::warning(this, "错误",
                                 "这本图书尚未被归还，\n无法删除");
            return;
        }
        if (row != -1) {
            QString value = ui->bookTable->item(row, 4)
                                ->text();  // 一定要放在前面，不然顺序错了就崩了
            ui->bookTable->removeRow(row);
            // 在数据库中删除这条记录
            QString sql = QString("DELETE FROM book_info WHERE book_number='") +
                          value + "';";
            database->exec(sql);
        }
    }
}

// 这几个是person页面各个按钮相关的行为
void initStudentTable(Database *database, QTableWidget *tableWidget) {
    database = Database::getInstance();
    database->connectDatabase();
    database->openDatabase();

    tableWidget->setColumnCount(6);
    tableWidget->setHorizontalHeaderLabels(
        QString("Id,账号,姓名,密码,性别,借阅图书").split(","));
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableWidget->setSortingEnabled(true);

    int columns;
    database->exec("select count(*) as row from student_info");
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    tableWidget->setRowCount(columns);

    database->exec("SELECT * FROM student_info;");

    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        tableWidget->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        tableWidget->setItem(
            i, 1, new QTableWidgetItem(query->value("account").toString()));
        tableWidget->setItem(
            i, 2, new QTableWidgetItem(query->value("name").toString()));
        tableWidget->setItem(
            i, 3, new QTableWidgetItem(query->value("password").toString()));
        tableWidget->setItem(
            i, 5, new QTableWidgetItem(query->value("borrow_book").toString()));

        if (query->value("sex").toInt() == 0) {
            tableWidget->setItem(i, 4, new QTableWidgetItem("男"));
        } else if (query->value("sex").toInt() == 1) {
            tableWidget->setItem(i, 4, new QTableWidgetItem("女"));
        } else {
            tableWidget->setItem(i, 4, new QTableWidgetItem("未知"));
        }
    }
}

void initAdminTable(Database *database, QTableWidget *tableWidget) {
    database = Database::getInstance();
    database->connectDatabase();
    database->openDatabase();

    tableWidget->setColumnCount(3);
    tableWidget->setHorizontalHeaderLabels(QString("Id,账号,密码").split(","));
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableWidget->setSortingEnabled(true);

    int columns;
    database->exec("select count(*) as row from admin_info");
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    tableWidget->setRowCount(columns);

    database->exec("SELECT * FROM admin_info;");

    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        tableWidget->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        tableWidget->setItem(
            i, 1, new QTableWidgetItem(query->value("account").toString()));
        tableWidget->setItem(
            i, 2, new QTableWidgetItem(query->value("password").toString()));
    }
}

void MainWindow::on_b_check_admin_clicked() {
    ui->personTable->clear();
    initAdminTable(database, ui->personTable);
}

void MainWindow::on_b_check_student_clicked() {
    ui->personTable->clear();
    initStudentTable(database, ui->personTable);
}

void MainWindow::on_b_add_person_clicked() {
    QSettings addItemSettings("./admin.ini", QSettings::IniFormat);
    AddAdminDialog adminDialog;
    if (adminDialog.exec() == QDialog::Accepted) {
        QString account = addItemSettings.value("admin/account").toString();
        QString password = addItemSettings.value("admin/password").toString();
        QString sql =
            QString("INSERT INTO admin_info VALUES (null, '%1', '%2');")
                .arg(account)
                .arg(password);
        if (!database->exec(sql)) {
            QMessageBox::warning(this, "错误", "管理员账号重复");
            return;
        }
        ui->personTable->clear();
        initAdminTable(database, ui->personTable);
    }
}

void MainWindow::on_b_delete_person_clicked() {
    if (QMessageBox::warning(this, "删除用户", "确定要删除这名用户吗?",
                             QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::Yes) {
        QString table;
        QString account;
        int column;
        if (ui->personTable->columnCount() == 6) {
            table = "student_info";
            column = 2;
        } else {
            table = "admin_info";
            column = 1;
        }
        int row = ui->personTable->currentRow();
        if (row == -1) {
            return;
        }
        if (ui->personTable->columnCount() != 6 &&
            ui->personTable->rowCount() == 1) {
            QMessageBox::warning(this, "错误", "仅剩一名管理员，不能删除账号");
            return;
        }
        if (ui->personTable->item(row, 5)->text().toInt() != 0) {
            QMessageBox::warning(this, "错误",
                                 "当前用户有尚未归还的图书，\n请尽快联系归还");
            return;
        }
        account = ui->personTable->item(row, column)->text();
        qDebug() << account;
        QString sql = QString("DELETE FROM %1 WHERE account='%2';")
                          .arg(table)
                          .arg(account);
        database->exec(sql);
        ui->personTable->removeRow(row);
    }
}

// 这是search页面的各种行为
void MainWindow::on_b_filter_book2_clicked() {
    QString value = ui->bookEdit2->text();
    if (value.length() == 0) {
        return;
    }
    QString key;
    // 备注，这里可以用QMap，但是不怎么了解，就先这样吧，只是写着麻烦点
    switch (ui->book_type2->currentIndex()) {
        case BOOK_NAME:
            key = "book_name";
            break;
        case BOOK_DOMAIN:
            key = "book_domain";
            break;
        case BOOK_AUTHOR:
            key = "book_author";
            break;
        case BOOK_PUBLISH:
            key = "book_publish";
            break;
        case BOOK_NUMBER:
            key = "book_number";
            break;
        default:
            return;
            break;
    }

    int columns;
    QString sql;
    sql = QString("select count(*) as row from book_info WHERE ") + key + "='" +
          value + "';";
    database->exec(sql);
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    if (columns == 0) {
        QMessageBox::information(this, "没有数据", "没有符合条件的结果");
        ui->bookEdit2->clear();
        return;
    }
    ui->bookTable2->setRowCount(columns);
    sql = QString("SELECT * FROM book_info WHERE ") + key + "='" + value + "';";
    database->exec(sql);
    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        ui->bookTable2->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        ui->bookTable2->setItem(
            i, 1, new QTableWidgetItem(query->value("book_name").toString()));
        ui->bookTable2->setItem(
            i, 2, new QTableWidgetItem(query->value("book_author").toString()));
        ui->bookTable2->setItem(
            i, 3,
            new QTableWidgetItem(query->value("book_publish").toString()));
        ui->bookTable2->setItem(
            i, 4, new QTableWidgetItem(query->value("book_number").toString()));
        ui->bookTable2->setItem(
            i, 5, new QTableWidgetItem(query->value("book_domain").toString()));
        ui->bookTable2->setItem(
            i, 6, new QTableWidgetItem(query->value("book_price").toString()));
        ui->bookTable2->setItem(
            i, 7, new QTableWidgetItem(query->value("book_date").toString()));
        if (query->value("is_borrowed").toInt() == 0) {
            ui->bookTable2->setItem(i, 8, new QTableWidgetItem("否"));
        } else {
            ui->bookTable2->setItem(i, 8, new QTableWidgetItem("是"));
        }
    }
}

void MainWindow::on_b_rollback_book2_clicked() {
    ui->bookEdit2->clear();
    initBookTable(database, ui->bookTable2);
}

void MainWindow::on_b_borrow_clicked() {
    if (QMessageBox::information(this, "借书", "确定要借走这本图书吗？",
                                 QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::No) {
        return;
    }

    int row = ui->bookTable2->currentRow();
    qDebug() << ui->bookTable2->item(row, 8)->text();
    if (ui->bookTable2->item(row, 8)->text() == QString("是")) {
        QMessageBox::warning(this, "图书已被借出",
                             "这本图书已经被借出，请重新选择");
        return;
    }
    QString bookNumber = ui->bookTable2->item(row, 4)->text();
    QString bookName = ui->bookTable2->item(row, 1)->text();
    QString currentTime =
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    qDebug() << bookNumber << bookName << currentTime;
    QString sql =
        QString("UPDATE book_info SET is_borrowed='%1' WHERE book_number='%2';")
            .arg(1)
            .arg(bookNumber);
    database->exec(sql);
    sql = QString(
              "INSERT INTO borrow_info VALUES(null, '%1', '%2', '%3', '%4', "
              "'%5');")
              .arg(bookNumber)
              .arg(bookName)
              .arg(studentAccount)
              .arg(studentName)
              .arg(currentTime);
    database->exec(sql);
    database->exec(QString("UPDATE student_info SET borrow_book=borrow_book+1 "
                           "WHERE account='%1'")
                       .arg(studentAccount));
    ui->bookTable2->item(row, 8)->setText("是");
}

// 这是return界面的各种行为
void initBorrowTable(Database *database, QTableWidget *tableWidget) {
    database = Database::getInstance();
    database->connectDatabase();
    database->openDatabase();

    tableWidget->setColumnCount(5);
    tableWidget->setHorizontalHeaderLabels(
        QString("Id,图书编号,图书名称,借阅时间,学生账号").split(","));
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableWidget->setSortingEnabled(true);

    int columns;
    database->exec("select count(*) as row from borrow_info");
    QSqlQuery *query = database->getQuery();
    query->first();
    columns = query->value(0).toInt();
    tableWidget->setRowCount(columns);

    database->exec("SELECT * FROM borrow_info;");

    query = database->getQuery();
    for (int i = 0; query->next(); i++) {
        tableWidget->setItem(
            i, 0, new QTableWidgetItem(query->value("id").toString()));
        tableWidget->setItem(
            i, 1, new QTableWidgetItem(query->value("book_number").toString()));
        tableWidget->setItem(
            i, 2, new QTableWidgetItem(query->value("book_name").toString()));
        tableWidget->setItem(
            i, 3, new QTableWidgetItem(query->value("borrow_time").toString()));
        tableWidget->setItem(
            i, 4,
            new QTableWidgetItem(query->value("student_account").toString()));
    }
}

void MainWindow::on_return_book_clicked() {
    if (QMessageBox::information(this, "还书", "确定要归还这本图书吗？",
                                 QMessageBox::Yes | QMessageBox::No) ==
        QMessageBox::No) {
        return;
    }
    int row = ui->borrowTable->currentRow();
    int id = ui->borrowTable->item(row, 0)->text().toInt();
    QString account = ui->borrowTable->item(row, 4)->text();
    QString number = ui->borrowTable->item(row, 1)->text();
    QString sql = QString("DELETE FROM borrow_info WHERE id=%1;").arg(id);
    database->exec(sql);
    sql = QString(
              "UPDATE student_info SET borrow_book=borrow_book-1 WHERE "
              "account='%1';")
              .arg(account);
    database->exec(sql);
    sql = QString("UPDATE book_info SET is_borrowed=0 WHERE book_number='%1';")
              .arg(number);
    database->exec(sql);
    initBorrowTable(database, ui->borrowTable);
    initBookTable(database, ui->bookTable2);
}

void MainWindow::on_reload_borrow_clicked() {
    ui->borrowTable->clear();
    initBorrowTable(database, ui->borrowTable);
}

void MainWindow::on_update_clicked() {
    ui->line->show();
    if (isAdmin) {
        ui->label_22->show();
        ui->label_23->show();
        ui->new_account->show();
        ui->new_account->setEnabled(true);
        ui->new_password->show();
        ui->new_password->setEnabled(true);
    } else {
        ui->label_23->show();
        ui->label_24->show();
        ui->label_25->show();
        ui->new_name->show();
        ui->new_name->setEnabled(true);
        ui->new_password->show();
        ui->new_password->setEnabled(true);
        ui->choose_sex->show();
        ui->choose_sex->setEnabled(true);
    }
    ui->confirm->show();
    ui->confirm->setEnabled(true);
    ui->cancel->show();
    ui->cancel->setEnabled(true);
}

void MainWindow::on_confirm_clicked() {
    QString sql;
    if (isAdmin) {
        QString newAccount, newPassword;
        if (ui->new_account->text().length() == 0 and
            ui->new_password->text().length() == 0) {
            return;
        }
        if (ui->new_account->text().length() == 0 and
            ui->new_password->text().length() != 0) {
            newPassword = ui->new_password->text();
            sql = QString(
                      "UPDATE admin_info SET password='%1' WHERE account='%2';")
                      .arg(newPassword)
                      .arg(adminAccount);
            database->exec(sql);
            adminPassword = newPassword;
            ui->d_password->setText(newPassword);
        }
        if (ui->new_account->text().length() != 0 and
            ui->new_password->text().length() == 0) {
            newAccount = ui->new_account->text();
            sql = QString(
                      "UPDATE admin_info SET account='%1' WHERE account='%2';")
                      .arg(newAccount)
                      .arg(adminAccount);
            database->exec(sql);
            adminAccount = newAccount;
            ui->d_account->setText(newAccount);
        }
        if (ui->new_account->text().length() != 0 and
            ui->new_password->text().length() != 0) {
            newAccount = ui->new_account->text();
            newPassword = ui->new_password->text();
            sql = QString(
                      "UPDATE admin_info SET account='%1', password='%2' "
                      "WHERE account='%3';")
                      .arg(newAccount)
                      .arg(newPassword)
                      .arg(adminAccount);
            database->exec(sql);
            adminAccount = newAccount;
            adminPassword = newPassword;
            ui->d_account->setText(newAccount);
            ui->d_password->setText(newPassword);
        }
        ui->new_account->clear();
        ui->new_password->clear();
    } else {
        QString newName, newPassword;
        int sex = ui->choose_sex->currentIndex();
        qDebug() << sex;
        if (ui->new_name->text().length() == 0 and
            ui->new_password->text().length() == 0) {
            sql = QString("UPDATE student_info SET sex=%1 WHERE account='%2';")
                      .arg(sex)
                      .arg(studentAccount);
            database->exec(sql);
        }
        if (ui->new_name->text().length() == 0 and
            ui->new_password->text().length() != 0) {
            newPassword = ui->new_password->text();
            sql = QString(
                      "UPDATE student_info SET sex=%1, password='%2' WHERE "
                      "account='%3';")
                      .arg(sex)
                      .arg(newPassword)
                      .arg(studentAccount);
            database->exec(sql);
            studentPassword = newPassword;
            ui->d_password->setText(newPassword);
            qDebug() << sql;
        }
        if (ui->new_name->text().length() != 0 and
            ui->new_password->text().length() == 0) {
            newName = ui->new_name->text();
            sql = QString(
                      "UPDATE student_info SET sex=%1, name='%2' WHERE "
                      "account='%3';")
                      .arg(sex)
                      .arg(newName)
                      .arg(studentAccount);
            database->exec(sql);
            studentName = newName;
            ui->d_name->setText(newName);
            qDebug() << sql;
        }
        if (ui->new_name->text().length() != 0 and
            ui->new_password->text().length() != 0) {
            newName = ui->new_name->text();
            newPassword = ui->new_password->text();
            sql =
                QString(
                    "UPDATE student_info SET sex=%1, name='%2', password='%3' "
                    "WHERE account='%4';")
                    .arg(sex)
                    .arg(newName)
                    .arg(newPassword)
                    .arg(studentAccount);
            database->exec(sql);
            studentName = newName;
            studentPassword = newPassword;
            ui->d_name->setText(newName);
            ui->d_password->setText(newPassword);
            qDebug() << sql;
        }
        ui->new_name->clear();
        ui->new_password->clear();
        studentSex = static_cast<StudentSex>(sex);
        if (sex == 0) {
            ui->d_sex->setText("男");
        } else if (sex == 1) {
            ui->d_sex->setText("女");
        } else {
            ui->d_sex->setText("未知");
        }
    }
}

void MainWindow::on_cancel_clicked() {
    ui->line->hide();
    ui->label_22->hide();
    ui->label_23->hide();
    ui->label_24->hide();
    ui->label_25->hide();
    ui->confirm->hide();
    ui->confirm->setDisabled(true);
    ui->cancel->hide();
    ui->cancel->setDisabled(true);
    ui->new_name->hide();
    ui->new_name->setDisabled(true);
    ui->new_account->hide();
    ui->new_account->setDisabled(true);
    ui->new_password->hide();
    ui->new_password->setDisabled(true);
    ui->new_name->clear();
    ui->new_account->clear();
    ui->new_password->clear();
    ui->choose_sex->hide();
    ui->choose_sex->setDisabled(true);
}
